// ==UserScript==
// @name         促销列表捕捉
// @namespace    http://tampermonkey.net/
// @version      0.1
// @description  促销列表捕捉
// @author       JFeng
// @require      https://cdn.bootcss.com/jquery/3.4.1/jquery.js
// @match        https://sellercentral.amazon.com/merchandising-new/create*
// @icon         https://img2.baidu.com/it/u=3337194467,672949329&fm=26&fmt=auto&gp=0.jpg
// @grant        none
// ==/UserScript==

(function () {
    'use strict';

    function sleep(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    function randomNum(min, max) {
        let Range = max - min;
        let Rand = Math.random();
        return min + Math.round(Rand * Range); // 四舍五入
    }

    function strRep(strValue) {
        let arr = strValue.split("-")
        let r = (arr[0] + "").trim() + " - " + (arr[1] + "").trim()
        return r;
    }

    function uuid() {
        let s = [];
        let hexDigits = "0123456789abcdef";
        for (let i = 0; i < 36; i++) {
            s[i] = hexDigits.substr(Math.floor(Math.random() * 0x10), 1);
        }
        s[14] = "4"; // bits 12-15 of the time_hi_and_version field to 0010
        s[19] = hexDigits.substr((s[19] & 0x3) | 0x8, 1); // bits 6-7 of the clock_seq_hi_and_reserved to 01
        s[8] = s[13] = s[18] = s[23] = "-";

        return s.join("").replace(/-/g, '');
    }

    window.onload = async function () {
        await sleep(8000)
        /**
         * 向数据库插入数据
         * */
        function save2mysql(table, pageData) {
            $.ajax({
                type: 'POST',
                dataType: 'json',
                url: 'http://amzapi.hieyoung.com:8281/records/' + table,
                headers: { 'Authorization': 'Basic aHl5OmhPOHVJRDNnZTNwbnJ2WXo2NXoz' },
                data: pageData,
                success: function (result) {
                    $("#smui-root > div.view-page > div > div.view-header.bg-white.px-32.py-16.mb-16.sticky > div > div.d-flex.ai-center.left > div.fs-24.lh-28.max-w-640").after("<b style='color:#50A10F;'>（更新到服务器成功）</b>");
                },
                error: function (xhr, status, error) {
                    $("#smui-root > div.view-page > div > div.view-header.bg-white.px-32.py-16.mb-16.sticky > div > div.d-flex.ai-center.left > div.fs-24.lh-28.max-w-640").after("<b style='color:#AC2306;'>（保存失败）</b>");
                },
            });
        }

        let count = 0;
        let storeName = $("#partner-switcher > button").text().split(" | ")
        while (true) {
            let arr = $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row > kat-table-cell:nth-child(2) > div.d-inline-block")

            for (let index = count; index < arr.length; index++) {
                let element = arr[index]

                let nthChild = index + 1
                let addContent = {
                    // 时间
                    "date": strRep($(element).text()),
                    // 店铺
                    "store_name": $("#partner-switcher > button").text(),
                    // 账号
                    "account": storeName[0],
                    // 站点
                    "site": storeName[1],
                    // 创建时间
                    "create_time": new Date(+new Date() + 8 * 3600 * 1000).toJSON().substr(0, 19).replace("T", " "),
                    "id": uuid(),
                    // 秒杀费用 
                    "deal_fee": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(5) > div").text(),
                    // 每件商品的折扣
                    "discount_per_unit": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(4) > div.d-inline-block.text-align-right").text(),
                    // 最低数量
                    "min_qty": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(4) > div.text-align-right.color-smui-dark-grey.color-smui-dark-grey").text(),
                    // 促销价格
                    "deal_price": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(3) > div:nth-child(1)").text(),
                    // 你的商品价格
                    "your_price": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(3) > div.color-smui-dark-grey.fs-12").text(),
                    // 商品名称
                    // a > slot > span
                    "name": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(1) > div > span.d-inline-block.ml-14 > div.max-w-350.ml-8.fs-13 > kat-link").attr("label"),
                    "sku": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(1) > div > span.d-inline-block.ml-14 > div.ml-8.color-smui-dark-grey.fs-12").text(),
                    // 交易类型
                    "type": $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row:nth-child(" + nthChild + ") > kat-table-cell:nth-child(1) > div > span.d-inline-block.ml-14 > div.ml-8.mt-10.smui-dark-grey > div > div.d-inline-block.ml-1.color-black").text(),
                }

                // alert(JSON.stringify(addContent))
                save2mysql("deal", addContent)
            }
            count = arr.length

            $("#loadMorebuttonDiv > div > a")[0].click()
            await sleep(10000)
        }

        /*
        for (let index = 0; index < 100; index++) {
            let arr = $("#smui-root > div.create-page > div.create-page-step-one.bg-azure > div > div.table-container > kat-table > kat-table-body > kat-table-row > kat-table-cell:nth-child(2) > div.d-inline-block")
            alert($(arr[count]).text())
            arr.each(function ())

            count = arr.length
            $("#loadMorebuttonDiv > div > a")[0].click()
            await sleep(2000)
        }*/

    }
})();